//
//  MNDDepositWebViewController.m
//  minidai
//
//  Created by 容贤郁 on 2018/3/16.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDDepositWebViewController.h"
#import "SYWebLoadingProgress.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDComplectedDepositViewController.h"
#import "UIImage+JKColor.h"
#import "MNDRiskAssessWebViewController.h"
#import "MNDMineViewController.h"
#import "MNDOpenTermsAuthViewController.h"

//设置交易密码结果回调页
#define kSetPaswordResult @"pay/pay_pwdset_jxreturn"
/*! 忘记交易密码 */
#define kForgotPassword   @"lapp/webreturn?sign=update_account_pwd"

/*! 开通存管点击返回按钮 */
#define kAuthBackButtonClick @"lapp/webreturn?sign=close"

/*! 绑卡点击返回个人中心按钮 */
#define kBindCardBack        @"ucenter"
/*! 立即投资 */
#define kSignTender          @"tender"
/*! 点击 设置密码，缴费授权，自动投标授权，自动债转授权 的回调地址 */
#define kAuthButtonClick(signStr)     [@"lapp/webreturn?sign=" stringByAppendingString:signStr]

@interface MNDDepositWebViewController () <UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property(nonatomic, strong) SYWebLoadingProgress *webLoadingProgress;

@property (nonatomic, copy) NSString *userPhone;

@property (nonatomic, assign) BOOL isLoadPaymentPassword;

@end

@implementation MNDDepositWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialBackButton];
    
    [self.webView loadHTMLString:self.htmlStr baseURL:nil];
    
    [self.view beginLoading];
    
    [self loadUserPhone];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    [self.navigationController.navigationBar setShadowImage:image];
    
}

//- (void)loadUserDepositStatus {
//
//    WeakSelf(self);
//    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"1"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
//
//        if (responseModel.status == ResponseFailure) {
//            NSDictionary *msgDict = responseModel.msg;
//            if ([msgDict.allKeys containsObject:@"sign"]) {
//                [NetworkProgressHUD hideHud];
//
//                [weakself configDepositWithModel:responseModel];
//            } else {
//                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
//            }
//        } else {
//            [self backAction:nil];
//        }
//    } onFailure:^(NSError *error) {
//        [NetworkProgressHUD showHudNetworkError:error];
//    }];
//}
//
//- (void)configDepositWithModel:(ResponseModel *)response {
//    NSString *signStr = response.msg[@"sign"];
//
//    //未开通存管
//    if ([signStr isEqualToString:kOpenAccount]) {
//
//        MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
//        realVC.fromNaviIndex = self.fromNaviIndex;
//
//        [self.navigationController pushViewController:realVC animated:YES];
//
//        return;
//    }
//
//    //未设置交易密码
//    if ([signStr isEqualToString:kSetPassword]) {
//
//        [self loadPaymentPassword];
//
//        return;
//    }
//
//    //设置缴费授权
//    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
//
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = self.fromNaviIndex;
//
//        [self.navigationController pushViewController:paymentVC animated:YES];
//
//        return;
//    }
//
//    //设置自动投标授权
//    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
//
//        MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
//        tenderVC.isResign = [signStr isEqualToString:kExpiredAutotender];
//        if (self.userPhone.length > 0) {
//            tenderVC.fromNaviIndex = self.fromNaviIndex;
//            tenderVC.phoneNumber = self.userPhone;
//
//            [self.navigationController pushViewController:tenderVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//
//        return;
//    }
//    //自动债转授权
//    if ([signStr isEqualToString:kSignAutoTransfer]) {
//
//        MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
//        if (self.userPhone.length > 0) {
//            transferVC.fromNaviIndex = self.fromNaviIndex;
//            transferVC.phoneNumber = self.userPhone;
//
//            [self.navigationController pushViewController:transferVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//
//        return;
//    }
//}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    NSLog(@"===============");
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webViewController = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webViewController.htmlStr = responseModel.data;
            webViewController.title = @"设置交易密码";
            webViewController.fromNaviIndex = weakself.fromNaviIndex;
            
            [weakself.navigationController pushViewController:webViewController animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

//授权三合一
- (void)goTermsAuthAction {
    MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
    openTermsAuthVC.fromNaviIndex = self.fromNaviIndex;
    [self.navigationController pushViewController:openTermsAuthVC animated:YES];
    return;
}

/**
 缴费授权
 */
- (void)signPaymentPasswordAction {
    MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
    paymentVC.fromNaviIndex = self.fromNaviIndex;
    
    [self.navigationController pushViewController:paymentVC animated:YES];
}

/**
 自动投标授权
 */
- (void)signAutoTenderAction {
    MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
    tenderVC.isResign = YES;
    if (self.userPhone.length > 0) {
        tenderVC.fromNaviIndex = self.fromNaviIndex;
        tenderVC.phoneNumber = self.userPhone;
        
        [self.navigationController pushViewController:tenderVC animated:YES];
    } else {
        [self loadUserPhone];
    }
}

- (void)signAutoTransferAction {
    MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
    if (self.userPhone.length > 0) {
        transferVC.fromNaviIndex = self.fromNaviIndex;
        transferVC.phoneNumber = self.userPhone;
        
        [self.navigationController pushViewController:transferVC animated:YES];
    } else {
        [self loadUserPhone];
    }
}

- (void)loadUserPhone {
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParam];
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
//            [weakself sendPhoneCaptcha:responseModel.data];
            weakself.userPhone = responseModel.data;
            //            weakself.userPhone.text = [weakself.userPhoneNum replaceWithAsteriskAtRange:NSMakeRange(3, 4)];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (NSMutableURLRequest *)addHTTPHeaderFieldWithRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //来源加入header
    if (kDevice_iPad) {
        [mutableRequest addValue:@"iPad" forHTTPHeaderField:@"WERTYUIOP"];
    } else {
        [mutableRequest addValue:@"iPhone" forHTTPHeaderField:@"WERTYUIOP"];
    }
    
    return mutableRequest;
}

#pragma mark - UIWebView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSMutableURLRequest *mutableRequest = [self addHTTPHeaderFieldWithRequest:request];
    request = [mutableRequest copy];
    
    NSLog(@"request url: %@", request.URL.absoluteString);
    
    NSString *requestStr = request.URL.absoluteString;
    //点击返回按钮
    if ([requestStr containsString:kAuthBackButtonClick]) {
        
        [self backAction:nil];
        
        return NO;
    }
    
    if ([requestStr containsString:kAuthButtonClick(kBindCardBack)]) {
        
        NSInteger tabBarSelectedIndex = self.tabBarController.selectedIndex;
        //返回我的页面
        if (tabBarSelectedIndex != self.tabBarController.viewControllers.count - 1) {
            [self.tabBarController setSelectedIndex:self.tabBarController.viewControllers.count - 1];
        }
        [self.navigationController popToRootViewControllerAnimated:YES];
        return NO;
    }
    //点击忘记交易密码
    if ([requestStr containsString:kForgotPassword]) {
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
        UINavigationController *naviVC = [storyboard instantiateViewControllerWithIdentifier:@"ResetPassworddNaviVC"];
        
        [self presentViewController:naviVC animated:YES completion:^{
            
        }];
        
        return NO;
    }
    //点击设置交易密码按钮
    if ([requestStr containsString:kAuthButtonClick(kSetPassword)] ) {
        
        if (!self.isLoadPaymentPassword) {
            self.isLoadPaymentPassword = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadPaymentPassword];
            });
            return NO;
        }
        return YES;
    }
    
    //点击缴费授权按钮
    if ([requestStr containsString:kAuthButtonClick(kSignPayment)]) {

        [self goTermsAuthAction];

        return NO;
    }

    //点击自动投标授权
    if ([requestStr containsString:kAuthButtonClick(kSignAutoTender)]) {

        [self goTermsAuthAction];

        return NO;
    }

    //点击自动债转授权
    if ([requestStr containsString:kAuthButtonClick(kSignAutoTransfer)]) {

        [self goTermsAuthAction];

        return NO;
    }
    //风险测评
    if ([requestStr containsString:kAuthButtonClick(kRiskEvaluation)]) {
        
        [self loadRiskInfo];
        
        return NO;
    }
    
    if ([requestStr containsString:kAuthButtonClick(kSignTender)]) {
        
        UIViewController *topViewController = self.navigationController.viewControllers.firstObject;
        if ([topViewController isKindOfClass:[MNDMineViewController class]]) {
            [self.tabBarController setSelectedIndex:1];
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [self backAction:nil];
        }
        
        return YES;
    }
    
    return YES;
}

- (void)loadRiskInfo {
    [NetworkProgressHUD showHud];
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        [NetworkProgressHUD hideHud];
        if (responseModel.status == ResponseFailure) {
            [weakself toRiskViewController:responseModel.data[@"risk_url"]];
        } else {
            [weakself backAction:nil];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

/**
 风险测评
 */
- (void)toRiskViewController:(NSString *)riskUrl {
    
    MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
    riskVC.webViewUrl = riskUrl;
    riskVC.indexOfViewController = self.fromNaviIndex;
    riskVC.title = @"风险测评";
    riskVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:riskVC animated:YES];
}

//- (void)loadDepositInfo {
//    [NetworkProgressHUD showHud];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self loadUserDepositStatus:YES];
//    });
//}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    _webLoadingProgress.frame = CGRectMake(0, 0, kScreenWidth, 2);
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress startProgressAnimation];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    if ([webView.request.URL.absoluteString containsString:kCustomerServiceURLStr]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('chat-view-window-header-back')[0].style.display='none';"];
            self.title = @"在线客服";
        });
    }
    [self.webLoadingProgress completedProgressAnimation];
    [self.view endLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.webLoadingProgress completedProgressAnimation];
    if (error.code == -999) {
        return;
    }
    
    if (error.code == 102 || error.code == -102) {
        return;
    }
    
    [NetworkProgressHUD showHudNetworkError:error];
    WeakSelf(self);
    SYBlankPageType blankType = [weakself.view blankPageTypeWithError:error];
    [self.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.webView reload];
            //            [weakself.view beginLoading];
        });
    }];
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.fromNaviIndex];
    [self.navigationController popToViewController:viewController animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
